<template>
  <div>
    <div id="map" style="height: 50vh;"></div>
    <div>
      <svg ref="svg" :width="1920" :height="500">
        <polygon :points="areas"></polygon>
      </svg>
    </div>
    <canvas ref="myCanvas" id="myCanvas"></canvas>
    <button @click="convertToBase64">toBase64</button>
    <div>面积：{{ area }}平方米</div>
    <div>中心点：{{ centerPoint }}</div>
    <div>编辑之后的面积：{{ editArea }}</div>
  </div>
</template>

<script>
import { akProxy } from '@/utils/ak';
import Provider from '@/utils/chinatmsproviders'; // 
import L from "leaflet";
import "@geoman-io/leaflet-geoman-free";
import "@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css";
import * as turf from '@turf/turf'
export default {
  name: 'TestDraw',
  data() {
    return {
      areas:'',
      coordinates: [
        { latitude: 46.45551476164039, longitude: 123.64277601242067 },
        { latitude: 46.45493361887058, longitude: 123.64286720752717 },
        { latitude: 46.45525883784618, longitude: 123.64718556404115 },
        { latitude: 46.45587046599942, longitude: 123.64707559347156 },
      ],
      url: '',
      centerPoint: '',
      area: '',
      map: null,
      editArea: '',
      points:[],
      base64:''
    }
  },
  mounted() {
    // let polygon = turf.polygon([this.arr]);
    // this.area = turf.area(polygon)
    Provider(L)
    this.initMap()
  },
  computed: {
    getPath() {
      const path = this.coordinates.reduce(
        (acc, { latitude, longitude }, index) => {
          const command = index === 0 ? "M" : "L";
          return `${acc} ${command} ${longitude},${latitude}`;
        },
        ""
      );
      return `${path} Z`;
    },
    pointsStr() {
      return this.points.map(point => `${point.x} ${point.y}`).join(', ');
    }
  },
  methods: {
    convertToBase64() {
      const svg = this.$refs.svg;
      const canvas = this.$refs.myCanvas;
      const ctx = canvas.getContext('2d');
      // 将SVG绘制到画布上
      const svgData = new XMLSerializer().serializeToString(svg);
      const svgURL = 'data:image/svg+xml;base64,' + btoa(svgData);
      const img = new Image();
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        // 将画布转换为base64编码的图像
        this.base64 = canvas.toDataURL('image/png');
      }
      img.src = svgURL;
    },
    initMap() {
      let that = this
      let map = null
      map = L.map("map", {
        //显示中心
        center: [45.763968, 126.591629],
        //当前显示等级
        zoom: 16,
        // 映射容器
        pmIgnore: false,
      });
      L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', { maxZoom: 18, minZoom: 5, key: akProxy.ak }).addTo(map);
      L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', { maxZoom: 18, minZoom: 5, key: akProxy.ak }).addTo(map);
      map.pm.addControls({
        position: "topright",
        drawCircle: false,
      });
      // 修改插件默认语言为中文
      map.pm.setLang("zh");
      map.on('pm:drawend', (e) => {
        console.log(e)
      })
      map.on('pm:dragend', (e) => {
        console.log(e)
      })
      // let layer = null
      map.on('pm:create', (e) => {
        console.log(e)
        console.log(e.layer._parts[0], "绘制坐标");
        const arr = []
        e.layer._parts[0].forEach(ele => {
          arr.push(ele.x+' '+ele.y)
        })
        console.log(arr.toString())
        this.areas = arr.toString()
        let pointArr = []
        e.layer._latlngs[0].forEach(ele => {
          pointArr.push([ele.lat, ele.lng])
        })
        pointArr.push(pointArr[0])
        console.log(pointArr)
        that.compu(pointArr)
        // e.on('pm:edit', ele => {
        //   console.log(ele)
        // })
      })
      map.on('pm:globaleditmodetoggled', e => {
        e.map.pm.getGeomanDrawLayers(true).on('pm:disable', e => {
          console.log(e.layer._latlngs)
          let pointArr = []
          e.layer._latlngs[0].forEach(ele => {
            pointArr.push([ele.lat, ele.lng])
          })
          pointArr.push(pointArr[0])
          console.log(pointArr)
          that.compu1(pointArr)
        });
      });
    },
    compu(val) {
      const polygon = turf.polygon([
        val
      ])
      this.area = turf.area(polygon)
      this.centerPoint = turf.centroid(polygon).geometry.coordinates;
      // const canvas = document.createElement('canvas');

    },
    compu1(val) {
      const polygon = turf.polygon([
        val
      ])
      this.editArea = turf.area(polygon)
    },
  },
}
</script>

<style scoped></style>
